// pages/my/setting/setting.js
const app = getApp();
Page({
  data: {
  },
  onLoad() {
    this.loadData();
  },
  bindblur(e) {
    if (e.detail.value === this.nickname) return;
    app.request('/api/user/profile', {nickname: e.detail.value}, 'POST').then(res => {
      console.log(res.data);
      if (res.data.code === 1) {
        app.globalData.userinfo.nickname = e.detail.value;
        wx.showToast({
          title: '昵称修改成功',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: '昵称修改失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error(err);
    });
  },
  getAvatar(e) {
    const that = this;
    wx.uploadFile({
      url: app.globalData.requestUrl + '/api/common/upload',
      filePath: e.detail.avatarUrl,
      header: {
        'TOKEN': app.globalData.token
      },
      name: 'file',
      success(res) {
        let data = JSON.parse(res.data);
        console.log('upload res', data);
        if (data.code === 1) {
          app.request('/api/user/profile', {avatar: data.data.url}, 'POST').then(resv => {
            console.log(resv.data);
            if (resv.data.code === 1) {
              that.setData({
                avatar: data.data.fullurl
              });
              app.globalData.userinfo.avatar = data.data.url;
              wx.showToast({
                title: '头像修改成功',
                icon: 'none'
              });
            } else {
              wx.showToast({
                title: '头像修改失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            console.error(err);
          });
        } else {
          wx.showToast({
            title: '上传失败，请重试',
            icon: 'none'
          });
        }
      },
      fail(err) {
        console.log('upload err', err);
      }
    })
  },
  loadData() {
    let nickname = app.globalData.userinfo.nickname ? app.globalData.userinfo.nickname : '默认昵称';
    let avatar = app.globalData.userinfo.avatar ? app.globalData.userinfo.avatar : 'https://6578-exam-4gpi8ydje868ff67-1327884539.tcb.qcloud.la/img/my/avatar.png';
    if (avatar.charAt(0) === '/') {
      avatar = app.globalData.requestUrl + avatar;
    }
    this.nickname = nickname;
    this.avatar = avatar;
    this.setData({
      nickname: nickname,
      avatar: avatar
    });
  }
})